/**
 * 通知工具函数
 */

import type {
  NotificationDetail,
  NotificationType as _NotificationType,
  TargetType as _TargetType,
  LikeArticleExtra,
  LikeCommentExtra,
  CommentExtra,
  ReplyExtra
} from "@/api/notification";

/** 额外数据类型联合 */
export type ExtraDataType =
  | LikeArticleExtra
  | LikeCommentExtra
  | CommentExtra
  | ReplyExtra
  | null;

/**
 * 安全解析 extraData JSON 字符串
 * @param extraData JSON 字符串
 * @returns 解析后的对象或 null
 */
export function parseExtraData<T = any>(
  extraData: string | null | undefined
): T | null {
  if (!extraData) return null;

  try {
    return JSON.parse(extraData) as T;
  } catch (error) {
    console.error("Failed to parse extraData:", error);
    return null;
  }
}

/**
 * 获取通知的完整上下文信息
 * @param notification 通知对象
 * @returns 上下文信息
 */
export function getNotificationContext(notification: NotificationDetail) {
  const extra = parseExtraData(notification.extraData);

  return {
    content: notification.content,
    extra,
    type: notification.type,
    targetType: notification.targetType
  };
}

/**
 * 根据通知信息构建目标 URL
 * @param notification 通知对象
 * @returns 目标 URL 或 null
 */
export function getTargetUrl(notification: NotificationDetail): string | null {
  // 优先使用新的 articleInfo 字段
  if (notification.articleInfo?.url) {
    // 如果有评论详情，跳转到评论位置
    if (notification.commentDetail?.id) {
      const baseUrl = sanitizeUrl(notification.articleInfo.url);
      return `${baseUrl}#comment-${notification.commentDetail.id}`;
    }
    return sanitizeUrl(notification.articleInfo.url);
  }

  // 兼容旧的 extraData 逻辑
  const extra = parseExtraData<any>(notification.extraData);

  switch (notification.type) {
    case "LIKE":
      // 点赞 - 通过targetType区分文章/评论
      if (notification.targetType === "article" && notification.targetId) {
        // 点赞文章
        return `/user/article/${notification.targetId}`;
      } else if (notification.targetType === "comment") {
        // 点赞评论 - 跳转到文章的评论位置
        if (notification.articleInfo?.id && notification.targetId) {
          return `/user/article/${notification.articleInfo.id}#comment-${notification.targetId}`;
        } else if (extra?.articleId && notification.targetId) {
          // 兼容旧数据
          return `/user/article/${extra.articleId}#comment-${notification.targetId}`;
        }
      }
      break;

    case "COLLECT":
      // 收藏 - 跳转到文章
      if (notification.targetId) {
        return `/user/article/${notification.targetId}`;
      }
      break;

    case "COMMENT":
    case "REPLY":
    case "MENTION":
      // 评论/回复/@提及 - 跳转到文章的评论位置
      if (extra?.articleId) {
        const commentId =
          notification.commentDetail?.id || notification.targetId;
        if (commentId) {
          return `/user/article/${extra.articleId}#comment-${commentId}`;
        }
      }
      break;

    case "FOLLOW":
      // 关注 - 跳转到用户主页
      if (notification.sender?.userId) {
        return `/user/profile/${notification.sender.userId}`;
      }
      break;

    case "SYSTEM":
      // 系统通知 - 如果有 target URL 就使用
      if (notification.target?.url) {
        return sanitizeUrl(notification.target.url);
      }
      break;

    default:
      return null;
  }

  return null;
}

/**
 * 清理 URL,确保是客户端路径
 * @param url 原始 URL
 * @returns 清理后的 URL
 */
function sanitizeUrl(url: string): string {
  if (!url) return url;

  let cleanUrl = url;

  // 如果是完整的 URL(包含协议),尝试提取路径部分
  try {
    if (url.startsWith("http://") || url.startsWith("https://")) {
      const urlObj = new URL(url);
      cleanUrl = urlObj.pathname + urlObj.search + urlObj.hash;
    }
  } catch (e) {
    console.warn("Failed to parse URL:", url, e);
  }

  // 将 /article/ 路径转换为 /user/article/ (用户端路径)
  if (cleanUrl.startsWith("/article/")) {
    cleanUrl = "/user" + cleanUrl;
  }

  return cleanUrl;
}

/**
 * 按日期分组通知列表
 * @param notifications 通知列表
 * @returns 分组后的通知对象
 */
export function groupNotificationsByDate(
  notifications: NotificationDetail[]
): Record<string, NotificationDetail[]> {
  const groups: Record<string, NotificationDetail[]> = {};

  notifications.forEach(notification => {
    const date = new Date(notification.createTime);
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);

    let key: string;
    if (date.toDateString() === today.toDateString()) {
      key = "今天";
    } else if (date.toDateString() === yesterday.toDateString()) {
      key = "昨天";
    } else {
      key = date.toLocaleDateString("zh-CN");
    }

    if (!groups[key]) {
      groups[key] = [];
    }
    groups[key].push(notification);
  });

  return groups;
}

/**
 * 格式化时间显示
 * @param time 时间字符串
 * @returns 格式化后的时间文本
 */
export function formatNotificationTime(time: string): string {
  if (!time) return "-";

  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`;
  } else {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const dayOfMonth = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${dayOfMonth}`;
  }
}
